package Sort.sort2022;

/**
 * 快速排序
 * @author leiwenkang <leiwenkang@kuaishou.com>
 * Created on 2022-04-11
 */
public class QuickSort {
    public static void main(String[] args) {
        int[] array = {3, 5, 8, 4, 1, 6, 2, 9, 7};
        quickSort(array);
        for (int i = 0; i < array.length; i++) {
            System.out.print(array[i]);
            System.out.print(" ");
        }
    }

    public static void quickSort(int[] array) {
        if (array == null || array.length == 0) {
            return;
        }
        quickSort(array, 0, array.length - 1);
    }

    public static void quickSort(int[] array, int low, int high) {
        if (low >= high) {
            return;
        }
        int pos = partition(array, low, high);
        quickSort(array, low, pos - 1);
        quickSort(array, pos + 1, high);
    }

    public static int partition(int[] array, int low, int high) {
        int value = array[low];

        while (low < high) {
            while (low < high && array[high] >= array[low]) {
                high--;
            }

            array[low] = array[high];

            while (low < high && array[low] <= array[high]) {
                low++;
            }

            array[high] = array[low];
        }

        array[low] = value;

        return low;
    }

}
